package net.zjitc.dao.impl;

import net.zjitc.dao.ProductDao;
import net.zjitc.domain.Product;
import net.zjitc.utils.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @version 1.0
 * @autho 赵静静
 * @date 2018/10/16 12:07
 */
public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> findAll() {
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        String sql = "select * from product";
        try {
            return  runner.query(sql,new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Product findById(String pid) {
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        String sql = "select * from product where pid = ?";
        try {
            return  runner.query(sql,new BeanHandler<>(Product.class),pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int add(Product p) {
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        String sql = "insert into product(pname,market_price,shop_price,image,pdesc,pdate,is_hot,csid)value(?,?,?,?,?,?,?,?)";
        try {
            return runner.update(sql,new Object[]{p.getPname(),p.getMarket_price(),p.getShop_price(),p.getImage(),p.getPdesc(),
             p.getPdate(),p.getIs_hot(),p.getCsid()});
        } catch (SQLException e) {
            e.printStackTrace();
        }
           return 0;
    }
}
